package com.kevis.zhunblog.admin.security.context;

import com.kevis.zhunblog.admin.security.entity.SecurityUser;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * UserContext
 *
 * @Author kevis
 * @Date 2023/3/31 16:32
 */
@Component
public class UserContext {

    /**
     * 获取当前登录用户的信息
     *
     * @return
     */
    public static Authentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication;
    }

    public static SecurityUser currentUser() {
        return null != getAuthentication() ? (SecurityUser) getAuthentication().getPrincipal() : null;
    }

    /**
     * 验证当前用户是否登录
     *
     * @return boolean 是否登录
     */
    public static boolean isAuthentication() {
        // if security session eq s-id is not null to index
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return !(auth instanceof AnonymousAuthenticationToken);
    }

    /**
     * SysUser 当前用户
     * */
    public SecurityUser getPrincipal(){
        try {
            return currentUser();
        } catch (NullPointerException e){
            return new SecurityUser();
        }
    }

    /**
     * Username 当前用户名
     * */
    public String getUsername(){ return getPrincipal().getUsername(); }

    /**
     * nickname 当前用户昵称
     * */
    //public String getRealName(){ return getPrincipal().getRealName(); }

    /**
     * UserId 用户编号
     * */
    public Integer getUserId(){ return getPrincipal().getUserId(); }

    /**
     * RoleId 角色编号
     * */
    public Integer getRoleId(){ return getPrincipal().getRoleId(); }

    /**
     * deptId 当前部门
     * */
    //public String getDeptId(){ return getPrincipal().getDeptId(); }

    /**
     * roles 角色列表
     * */
    //public List<SysRole> getRoles() { return getPrincipal().getRoles(); }

}
